package core

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github/kadycui/gids/middleware"
	"github/kadycui/gids/model"
	"github/kadycui/gids/pkg/postgre"
	"net/http"
	"time"
)

func EmpAdd(ctx *gin.Context) {
	middleware.Log.Info("员工添加")
	var employee model.Employee

	// 绑定 JSON 请求体到 employee 结构体
	if err := ctx.ShouldBindJSON(&employee); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 设置 Created 字段为当前时间
	employee.Created = time.Now()

	// 插入到数据库
	db := postgre.GetDB()
	if err := db.Create(&employee).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 返回成功响应
	ctx.JSON(http.StatusOK, gin.H{"message": "Employee created successfully", "employee": employee})

}

func QueryOneEmployee(ctx *gin.Context) {
	middleware.Log.Info("查询一个员工")
	var employee model.Employee

	id := ctx.Query("id")

	db := postgre.GetDB()

	if id == "0" {
		var employees []model.Employee
		result := db.Find(&employees)
		// 检查查询结果
		if result.Error != nil {
			ctx.JSON(http.StatusNotFound, gin.H{"error": "Employee not found"})
			return
		}

		ctx.JSON(http.StatusOK, employees)

	}
	// 查询员工
	if err := db.First(&employee, id).Error; err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "Employee not found"})
		return
	}
	fmt.Println(employee)
	ctx.JSON(http.StatusOK, employee)
}

func UpdateEmployee(ctx *gin.Context) {
	id := ctx.Query("id")

	var updateEmployee model.Employee
	db := postgre.GetDB()

	// 绑定请求体到 User 结构体
	if err := ctx.BindJSON(&updateEmployee); err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}

	var employee model.Employee
	// 查找用户
	if err := db.First(&employee, id).Error; err != nil {
		ctx.JSON(404, gin.H{"error": "User not found"})
		return
	}

	// 更新用户字段
	db.Model(&employee).Updates(updateEmployee)

	ctx.JSON(http.StatusOK, employee)
}

func DeleteEmployee(ctx *gin.Context) {
	id := ctx.Query("id")
	db := postgre.GetDB()
	//var employee model.Employee
	// 尝试删除指定 ID 的用户
	result := db.Delete(&model.Employee{}, id)

	// 检查是否删除成功
	if result.Error != nil {
		ctx.JSON(500, gin.H{"error": result.Error.Error()})
		return
	}

	if result.RowsAffected == 0 {
		ctx.JSON(404, gin.H{"message": "employee not found"})
		return
	}

	// 返回成功消息
	ctx.JSON(200, gin.H{"message": "employee deleted successfully"})
}
